package org.example.wxdemo.controller;

import org.example.wxdemo.model.*;
import org.example.wxdemo.util.XmlUtils;
import org.example.wxdemo.util.SignatureUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

@Slf4j
@RestController
@RequestMapping("/wx")
public class WxMessageController {
    
    private static final String TOKEN = "test"; // 微信服务器验证token

    /**
     * 处理微信服务器验证请求
     */
    @GetMapping("/message")
    public String verifyServer(@RequestParam(name = "signature") String signature,
                             @RequestParam(name = "timestamp") String timestamp,
                             @RequestParam(name = "nonce") String nonce,
                             @RequestParam(name = "echostr") String echostr) {
        log.info("收到微信服务器验证请求 - signature: {}, timestamp: {}, nonce: {}, echostr: {}", 
                   signature, timestamp, nonce, echostr);

        if (SignatureUtils.checkSignature(signature, timestamp, nonce, TOKEN)) {
            log.info("微信服务器验证通过");
            return echostr;
        }

        log.warn("微信服务器验证失败");
        return "fail";
    }

    @PostMapping(value = "/message", consumes = MediaType.TEXT_XML_VALUE, produces = MediaType.TEXT_XML_VALUE)
    public String handleMessage(@RequestBody String requestBody) {
        try {
            log.info("Received message from WeChat server: {}", requestBody);
            
            // 根据消息类型处理不同的消息
            if (requestBody.contains("<MsgType><![CDATA[text]]></MsgType>")) {
                WxTextMessage textMessage = XmlUtils.fromXml(requestBody, WxTextMessage.class);
                return handleTextMessage(textMessage);
            } else if (requestBody.contains("<MsgType><![CDATA[image]]></MsgType>")) {
                WxImageMessage imageMessage = XmlUtils.fromXml(requestBody, WxImageMessage.class);
                return handleImageMessage(imageMessage);
            }
            
            // 如果是其他类型的消息，返回success表示不处理
            return "success";
        } catch (Exception e) {
            log.error("Error processing WeChat message", e);
            // 发生异常时返回success，避免微信服务器重试
            return "success";
        }
    }

    private String handleTextMessage(WxTextMessage message) {
        log.info("收到文本消息 - 发送者: {}, 内容: {}", message.getFromUserName(), message.getContent());
        
        try {
            // 创建回复消息
            WxTextResponseMessage response = new WxTextResponseMessage();
            response.setToUserName(message.getFromUserName());
            response.setFromUserName(message.getToUserName());
            response.setCreateTime(System.currentTimeMillis() / 1000);
            response.setContent("收到你的消息：" + message.getContent());
            
            // 将响应消息转换为XML
            return XmlUtils.toXml(response);
        } catch (Exception e) {
            log.error("处理文本消息失败", e);
            return "success";
        }
    }

    private String handleImageMessage(WxImageMessage message) {
        log.info("收到图片消息 - 发送者: {}, MediaId: {}", 
                   message.getFromUserName(), message.getMediaId());
        
        try {
            // 创建回复消息（使用收到的图片回复）
            WxImageResponseMessage response = new WxImageResponseMessage();
            response.setToUserName(message.getFromUserName());
            response.setFromUserName(message.getToUserName());
            response.setCreateTime(System.currentTimeMillis() / 1000);
            
            WxImageResponseMessage.Image image = new WxImageResponseMessage.Image();
            image.setMediaId(message.getMediaId());
            response.setImage(image);
            
            // 将响应消息转换为XML
            return XmlUtils.toXml(response);
        } catch (Exception e) {
            log.error("处理图片消息失败", e);
            return "success";
        }
    }
} 